// 
import { t } from "@/lang/i18n";
import { getConfigFileList, getConfigFile } from "@/services/apis/instance";
import { getInstanceConfigByType, type InstanceConfigs } from "@/hooks/useInstance";
import { reportErrorMsg } from "@/tools/validator";

/**
 * 获取配置文件列表，并获取第一个配置文件的详细信息
 * @param type 配置类型（例如 "minecraft/java"）
 * @param instanceId 实例 ID
 * @param daemonId 守护进程 ID
 * @returns Promise 对象，resolve 后返回 { list, detailed }
 *          list：经过比对处理后的配置文件列表
 *          detailed：包含第一个配置文件详细信息的数组（如果存在）
 */
export async function fetchConfigListAndFirstDetail(
  type: string,
  instanceId: string,
  daemonId: string
): Promise<{ list: InstanceConfigs[]; detailed: any[] }> {
  try {

    const configFiles: InstanceConfigs[] = getInstanceConfigByType(type);

    const files: string[] = configFiles.map((item) => item.path);


    const { execute, state: realFiles } = getConfigFileList();
    await execute({
      params: {
        uuid: instanceId,
        daemonId: daemonId,
      },
      data: {
        files: files,
      },
    });

    if (!realFiles.value) {
      reportErrorMsg(t("TXT_CODE_83e553fc"));
      return { list: [], detailed: [] };
    }


    realFiles.value.forEach((v: { file: string }) => {
      configFiles.forEach((z: InstanceConfigs) => {
        if (z.path === v.file) {
 
          configFiles.forEach((p: InstanceConfigs) => {
            if (p.path === z.path && p.check) {
              z.conflict = true;
            }
          });
          z.check = true;
        }
      });
    });


    const InstanceConfigsList: InstanceConfigs[] = configFiles;


    const detailedConfigArray: any[] = [];
    if (InstanceConfigsList.length > 0) {
      const firstConfig = InstanceConfigsList[0];

      const { execute: reqConfigFile, state: configFile } = getConfigFile();
      await reqConfigFile({
        params: {
          uuid: instanceId,
          daemonId: daemonId,
          fileName: firstConfig.path, 
          type: firstConfig.type, 
        },
      });
      if (configFile.value) {
        detailedConfigArray.push(configFile.value);
      }
    }


    return {
      list: InstanceConfigsList,
      detailed: detailedConfigArray,
    };
  } catch (error: any) {
    console.error(error);
    reportErrorMsg(error.message);
    return { list: [], detailed: [] };
  }
}
